package cn.linkstudy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.linkstudy.entity.User;
import cn.linkstudy.mapper.UserMapper;
import cn.linkstudy.service.UserService;
import cn.linkstudy.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import cn.linkstudy.util.HttpUtils;
import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean register(User user) {
        // 注册时自动分配 username
        if (!StringUtils.hasText(user.getUsername())) {
            user.setUsername("用户" + String.format("%04d", new Random().nextInt(10000)));
        }
        // 检查用户名是否已存在
        if (findByUsername(user.getUsername()) != null) {
            return false;
        }
        // 检查手机号是否已存在
        // if (findByPhone(user.getPhone()) != null) {
        // return false;
        // }
        return save(user);
    }

    @Override
    public User findByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return getOne(queryWrapper);
    }

    @Override
    public User findByPhone(String phone) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        return getOne(queryWrapper);
    }

    @Override
    public boolean updateUserInfo(User user) {
        // 只保留空实现或直接返回false，因为已无可更新字段
        return false;
    }

    @Override
    public boolean sendSmsCode(String phone) {
        long now = System.currentTimeMillis();
        // 相关的字段、类、方法实现。
        // 生成6位验证码
        String code = String.format("%06d", new Random().nextInt(999999));
        System.out.println("Generated SMS code: " + code + " for phone: " + phone);
        // 调用阿里云短信API
        try {
            String host = "https://gyytz.market.alicloudapi.com";
            String path = "/sms/smsSend";
            String method = "POST";

            //替换为你的AppCode
            String appcode = "xxxxxxxx";
            //a36d1bbd71ac4f05aa8ca36aef73c8d6
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "APPCODE " + appcode);
            Map<String, String> querys = new HashMap<>();
            querys.put("mobile", phone);
            querys.put("param", "{\"code\":\"" + code + "\",\"minute\":\"" + 1 + "\"}"); // 验证码有效期1分钟
            querys.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");//短信签名ID
            querys.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");//短信模板ID
            Map<String, String> bodys = new HashMap<>();
            System.out.println("Sending SMS request with params: " + querys);
            String resp = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println("SMS API response: " + resp);
            if (resp != null && resp.contains("\"code\":\"0\"")) {
                System.out.println("SMS sent successfully");
                // 验证码只能用一次，不再存储在内存中
                return true;
            } else {
                System.out.println("SMS sending failed, response: " + resp);
                throw new RuntimeException("短信发送失败，请稍后重试");
            }
        } catch (Exception e) {
            System.out.println("SMS sending exception: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("短信发送失败: " + e.getMessage());
        }
    }

    @Override
    public String loginByPhoneCode(String phone, String code) {
        // 验证码校验逻辑略...
        User user = findByPhone(phone);
        if (user == null) {
            // 自动注册
            user = new User();
            user.setPhone(phone);
            user.setUsername("用户" + String.format("%04d", new Random().nextInt(10000)));
            user.setCreateTime(new java.util.Date());
            save(user);
        }
        // 生成token
        String token = jwtUtil.generateToken(user.getId(), user.getUsername());
        return token;
    }

    @Override
    public boolean updateAvatarColor(Long userId, String avatarColor) {
        return userMapper.updateAvatarColor(userId, avatarColor) > 0;
    }
}